﻿// =================================================================
//  Copyright (c) "David R. Guindo", Software architect
//  
//  This code is released under the terms of the Apache License, Version 2.0,
//  http://www.apache.org/licenses/LICENSE-2.0
//  
//  THIS CODE AND INFORMATION ARE PROVIDED WITHOUT WARRANTIES,
//  WITHOUT LIMITING COMMERCIAL OR PARTICULAR USE.
// =================================================================

namespace ScreenManagerDemo
{
   using System.Windows;
   using System.Windows.Media;

   /// <summary>
   /// 
   /// </summary>
   public static class WpfHelpers
   {
      public static T FindAncestorOrSelf<T>(DependencyObject obj) where T : DependencyObject
      {
         while (obj != null)
         {
            var objTest = obj as T;
            if (objTest != null)
            {
               return objTest;
            }
            obj = GetParent(obj);
         }

         return null;
      }

      private static DependencyObject GetParent(DependencyObject obj)
      {
         if (obj == null)
         {
            return null;
         }

         var ce = obj as ContentElement;
         if (ce != null)
         {
            DependencyObject parent = ContentOperations.GetParent(ce);
            if (parent != null)
            {
               return parent;
            }

            var fce = ce as FrameworkContentElement;
            return fce != null ? fce.Parent : null;
         }

         return VisualTreeHelper.GetParent(obj);
      }
   }
}